<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取所有商品</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 8px 12px;
            border: 1px solid #ccc;
            text-align: left;
        }

        th {
            background-color: #f4f4f4;
        }
    </style>
</head>
<body>
<h1>商品列表</h1>

<table id="product-table">
    <thead>
    <tr>
        <th>商品ID</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>分类</th>
    </tr>
    </thead>
    <tbody>
    <!-- 商品数据将动态填充到这里 -->
    </tbody>
</table>

<script>
    // 获取表格元素
    const productTableBody = document.getElementById('product-table').getElementsByTagName('tbody')[0];

    // 页面加载时自动加载商品数据
    window.onload = function() {
        fetch('http://localhost:8080/products')  // 确认路径和端口正确
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应失败');
                }
                return response.json();
            })
            .then(products => {
                // 处理成功响应
                productTableBody.innerHTML = '';
                products.forEach(product => {
                    const row = productTableBody.insertRow();
                    row.insertCell(0).textContent = product.id;
                    row.insertCell(1).textContent = product.name;
                    row.insertCell(2).textContent = product.price;
                    row.insertCell(3).textContent = product.category;
                });
            })
            .catch(error => {
                console.error('请求失败:', error);
                alert('加载数据失败，请查看控制台获取详细错误信息。');
            });
    };
</script>
</body>
</html>
